﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;

namespace MvcImproved.Generic.Controls
{
	public class Label<TDataItem> : NamedGenericControl<TDataItem, string>
	{
		public Label(Func<TDataItem, string> valueMember)
			: base(valueMember)
		{
			AutoId = true;
		}

		public string For
		{ get; set; }

		private Control ForControl;

		protected override void Render(HtmlTextWriter writer)
		{
			base.Render(writer);

			string classValue;
			if (Attributes.TryGetValue("cssclass", out classValue) || Attributes.TryGetValue("class", out classValue))
				writer.AddAttribute(HtmlTextWriterAttribute.Class, classValue);

			string memberValue;
			if (!DesignMode)
				memberValue = (DataValue == null) ? null : ValueMemberLambda(DataValue);
			else
				memberValue = ValueMember;
			
			if ((memberValue != null) && (ForControl != null))
			{
				writer.AddAttribute(HtmlTextWriterAttribute.For, ForControl.ClientID);
				writer.RenderBeginTag(HtmlTextWriterTag.Label);
				writer.Write(memberValue);
				writer.RenderEndTag();
			}
		}

		public override void DataBind()
		{
			base.DataBind();

			if (For != null)
			{
				var parentCheck = Parent;
				while (parentCheck != null)
				{
					ForControl = parentCheck.FindControl(For);
					if (ForControl != null)
						break;
					parentCheck = parentCheck.Parent;
				}
				if (ForControl == null)
					throw new InvalidOperationException(String.Format("Could not find control {0}", For));
			}
		}
	}

	// Non-generic version of the control that's used in the actual markup
	[ControlBuilder(typeof(GenericControlBuilder))]
	[GenericControlType(typeof(Label<>), MemberValue = "ValueMember", GenericParameters = "ModelType")]
	public class Label : Label<object>
	{
		public Label()
			: base(null)
		{ }

		public string ModelType
		{
			get;
			set;
		}
	}
}
